// Promise 方式的 AJAX
function ajax (url) {
  return new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.responseType = 'json';
    xhr.onload = function () {
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    }
    xhr.send();
  });
}

// Promise.all([
//   ajax('/api/users.json'),
//   ajax('/api/posts.json')
// ]).then(value => {
//   console.log(value); // [{name: "wubo", age: 27}, {post: 123}]
// })

const timeout = new Promise((resolve, reject) => {
  setTimeout(() => reject(new Error('timeout'), 500));
})
Promise.race([
  ajax('/api/posts.json'), 
  timeout,
]).then(value => {
  console.log(value);
}).catch(error => {
  console.log(error);
})
